// 用户状态管理

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { userLogin, userLogout, getLoginUser } from '@/api/user'
import type { LoginUserVO, UserLoginRequest } from '@/types/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<LoginUserVO | null>(null)
  const token = ref<string>('')
  
  // 计算属性
  const isLoggedIn = computed(() => !!userInfo.value)
  const isAdmin = computed(() => userInfo.value?.userType === 'admin')
  
  // 登录
  const login = async (loginData: UserLoginRequest) => {
    try {
      const response = await userLogin(loginData)
      userInfo.value = response.data
      // 假设后端返回token，实际根据后端实现调整
      const savedToken = localStorage.getItem('token') || 'mock-token'
      token.value = savedToken
      localStorage.setItem('token', savedToken)
      localStorage.setItem('userInfo', JSON.stringify(response.data))
      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }
  
  // 注销
  const logout = async () => {
    try {
      await userLogout()
      userInfo.value = null
      token.value = ''
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    } catch (error) {
      console.error('注销失败:', error)
      // 即使接口失败也清除本地数据
      userInfo.value = null
      token.value = ''
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
  
  // 获取当前用户信息
  const getCurrentUser = async () => {
    try {
      const response = await getLoginUser()
      userInfo.value = response.data
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }
  
  // 初始化用户信息（从本地存储恢复）
  const initUserInfo = () => {
    const savedToken = localStorage.getItem('token')
    const savedUserInfo = localStorage.getItem('userInfo')
    
    if (savedToken && savedUserInfo) {
      token.value = savedToken
      try {
        userInfo.value = JSON.parse(savedUserInfo)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        localStorage.removeItem('userInfo')
        localStorage.removeItem('token')
      }
    }
  }
  
  return {
    // 状态
    userInfo,
    token,
    // 计算属性
    isLoggedIn,
    isAdmin,
    // 方法
    login,
    logout,
    getCurrentUser,
    initUserInfo
  }
}, {
  persist: true
}) 